<?php
/**
 * 小i智能聊天模块
 * @author 回忆QQ125879930
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

class Huiyi_xiaoiModuleProcessor extends WeModuleProcessor {

    public function respond() {
        global $_W;
        $msg = $this->message['content'];
        $openid = $this->message['from'];
        $expire = intval($this->module['config']['expire']);
        $app_key = $this->module['config']['appKey'];
        $app_secret = $this->module['config']['appSecret'];

        if(!$expire) {
            $expire = 600;
        }

        if(!$this->inContext) {
            $this->beginContext($expire);
            $content ='小i见到您好开心，如果您要做其他操作，回复“退出”回到普通模式！';
        } else {
            if ($msg == '退出') {
                $this->endContext();
                $content = '小i走了，欢迎再来哦~';
            } else {
                if ($status['http_code'] = 200) {
                    $content = $this->xiaoi($app_key, $app_secret, $msg, $openid);
                } else {
                    $content = '那个...小i不知道怎么回答您，要不您发送[退出]再发：[梦梦]和梦梦姐聊聊？';
                }
            }
        }

        return $this->respText($content);
    }

    private function xiaoi($app_key="ZsSiMVnYbcsu", $app_secret="epBcVFnthozPrQKvl8z4", $msg, $openid) {

        $realm = "xiaoi.com";
        $method = "POST";
        $uri = "/ask.do";
        $nonce="";
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        for ( $i = 0; $i < 40; $i++)
            $nonce .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        $HA1 = sha1($app_key . ":" . $realm . ":" . $app_secret);
        $HA2 = sha1($method . ":" . $uri);
        $sign = sha1($HA1 . ":" . $nonce . ":" . $HA2);

        $msg = urlencode($msg);
        $openid = urlencode($openid);
        $platform = "weixin";
        $type = "0";
        $url = "http://nlp.xiaoi.com/ask.do";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth:	app_key="'.$app_key.'", nonce="'.$nonce.'", signature="'.$sign.'"'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "question=".$msg."&userId=".$openid."&platform=".$platform."&type=".$type);//question=你好&userId=aaa&platform=custom&type=1


        $data = curl_exec($ch);
        $status = curl_getinfo($ch);
        $errno = curl_errno($ch);
        curl_close($ch);

        return $data;
    }
}